import sys

from satchmo_tuning.models import CategoryTuning
from satchmo_tuning.management.commands import UploadCommand

class Command(UploadCommand):
    help = 'Uploads categories from specified CSV file.'

    def handle_reader(self, reader, site, encoding):

        row_count = 0
        for row in reader:
            row_count += 1
            if len(row) != 3:
                sys.stderr.write(self.style.ERROR("Wrong columns count for row %s %s\n" % (row_count, row)))
            code, parent_code, name = [unicode(c, encoding).strip() for c in row]

            category = self.get_category(code)
            if category:
                sys.stderr.write(self.style.ERROR("Category code [%s] is already exists\n" % code))
            else:
                parent_category = None
                if parent_code:
                    parent_category = self.get_category(parent_code)
                CategoryTuning.objects.create(
                            site=site, code=code, slug=code, parent=parent_category, name=name)
